//
//  WmcCollectionViewEmpty.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/10/24.
//

import Foundation

// MARK: - [WmcCollectionViewEmptyDelegate]

protocol WmcCollectionViewEmptyDelegate {
    /// 空视图数据源
    func CollectionViewEmpty() -> Int
    /// 指定空视图代理
    func CollectionViewEmptyView(_ CollectionView: UICollectionView) -> WmcBaseView?
}

extension WmcCollectionViewEmptyDelegate {
    /// 默认空视图（如果没设置的话）
    /// - Parameter CollectionView: CollectionView description
    /// - Returns: description
    func CollectionViewEmptyView(_ CollectionView: UICollectionView) -> WmcBaseView? {
        return WmcDefaultEmptyView(frame: .zero)
    }
}

// MARK: - [CollectionViewAssociateKeys]

struct CollectionViewAssociateKeys {
    /// 空视图代理
    static var WmcEmptyDelegate: WmcCollectionViewEmptyDelegate?
    /// 空视图
    static var WmcEmptyView: WmcBaseView?
}

extension UICollectionView {
    func wmcReloadData() {
        self.showEmpty()
        self.reloadData()
    }

    /// 代理
    var emptyDelegate: WmcCollectionViewEmptyDelegate? {
        set {
            objc_setAssociatedObject(self, &CollectionViewAssociateKeys.WmcEmptyDelegate, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, &CollectionViewAssociateKeys.WmcEmptyDelegate) as? WmcCollectionViewEmptyDelegate
        }
    }

    /// 空视图
    var emptyView: WmcBaseView? {
        set {
            objc_setAssociatedObject(self, &CollectionViewAssociateKeys.WmcEmptyView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, &CollectionViewAssociateKeys.WmcEmptyView) as? WmcBaseView
        }
    }

    /// 展示空 视图
    /// - Returns: description
    func showEmpty() {
        let isEmpty = (self.emptyDelegate?.CollectionViewEmpty() ?? 0) > 0 ? false : true
        if isEmpty {
            // 显示
            emptyView = (emptyView != nil) ? emptyView : (self.emptyDelegate?.CollectionViewEmptyView(self) != nil ? self.emptyDelegate?.CollectionViewEmptyView(self) : WmcBaseView())!
            self.addSubview(emptyView!)
        } else {
            // 移除
            self.emptyView?.removeFromSuperview()
        }
    }
}
